package it.polimi.comorazio.fragments;

import it.polimi.comorazio.R;
import it.polimi.comorazio.activities.ArchitectDetailActivity;
import it.polimi.comorazio.activities.PointOfInterestDetailActivity;
import it.polimi.comorazio.activities.PointOfInterestListActivity;
import it.polimi.comorazio.activities.Tour;
import it.polimi.comorazio.data.ArchitectVo;
import it.polimi.comorazio.data.DataBaseHelper;
import it.polimi.comorazio.data.ImageVo;
import it.polimi.comorazio.data.PointOfInterestVo;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

/**
 * A fragment representing a single PointOfInterest detail screen. This fragment
 * is either contained in a {@link PointOfInterestListActivity} in two-pane mode
 * (on tablets) or a {@link PointOfInterestDetailActivity} on handsets.
 */
public class PointOfInterestDetailFragment extends Fragment {
	/**
	 * The fragment argument representing the item ID that this fragment
	 * represents.
	 */
	public static final String ARG_ITEM_ID = "item_id";

	public PointOfInterestVo poi = null;
	public ImageVo image = null;
	private List<ImageVo> imagesList = new ArrayList<ImageVo>();
	private List<ArchitectVo> architectsList = new ArrayList<ArchitectVo>();

	/**
	 * Mandatory empty constructor for the fragment manager to instantiate the
	 * fragment (e.g. upon screen orientation changes).
	 */
	public PointOfInterestDetailFragment() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (getArguments().containsKey(ARG_ITEM_ID)) {
			// Load the dummy content specified by the fragment
			// arguments. In a real-world scenario, use a Loader
			// to load content from a content provider.
			// TODO Cannot use CursorLoader because the component in charge of
			// updating the view must be an adapter and those only work on
			// ListView, GridView or Spinner
			DataBaseHelper dbHelper = new DataBaseHelper(getActivity());
			dbHelper.createDataBase();
			dbHelper.openDataBase();
			Cursor c = dbHelper.getPointOfInterestById(Integer
					.parseInt(getArguments().getString(ARG_ITEM_ID)));
			poi = new PointOfInterestVo(c, 0,
					DataBaseHelper.getCurrentLocale(getActivity()));
			c.close();
			c = dbHelper.getImagesOfPointOfInterestById(Integer
					.parseInt(getArguments().getString(ARG_ITEM_ID)));
			image = new ImageVo(c, 0);
			c.close();
			c = dbHelper.getImagesOfPointOfInterestById(poi.getId());
			c.moveToFirst();
			while (!c.isAfterLast()) {
				imagesList.add(new ImageVo(c, c.getPosition()));
				c.moveToNext();
			}
			c.close();
			c = dbHelper.getArchitectsByPointOfInterestId(poi.getId());
			c.moveToFirst();
			while (!c.isAfterLast()) {
				architectsList.add(new ArchitectVo(c, c.getPosition(),
						DataBaseHelper.getCurrentLocale(getActivity())));
				c.moveToNext();
			}
			c.close();
			dbHelper.close();
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		final View rootView = inflater.inflate(
				R.layout.fragment_pointofinterest_detail, container, false);

		if (poi != null && image != null) {
			getActivity().setTitle("> " + poi.getName());
			((TextView) rootView.findViewById(R.id.pointofinterest_address))
					.setText(poi.getAddress());
			((TextView) rootView.findViewById(R.id.pointofinterest_description))
					.setText(poi.getDescription());

			// Instantiate a ViewPager and a PagerAdapter
			final ViewPager mPager = (ViewPager) rootView
					.findViewById(R.id.pager);

			mPager.setAdapter(new FragmentPagerAdapter(getActivity()
					.getSupportFragmentManager()) {

				@Override
				public int getCount() {
					return imagesList.size();
				}

				@Override
				public Fragment getItem(int position) {
					Bundle arguments = new Bundle();
					arguments.putString(ImageFragment.ARG_POSITION, null);
					arguments.putInt(
							ImageFragment.ARG_RESOURCE_ID,
							imagesList.get(position).getImageIdentifier(
									getActivity().getResources()));

					ImageFragment fragment = new ImageFragment();
					fragment.setArguments(arguments);

					return fragment;
				}
			});

			OnPageChangeListener changer = new OnPageChangeListener() {
				@Override
				public void onPageSelected(int pos) {
					if (pos == 0) {
						((Button) rootView.findViewById(R.id.prev_image))
								.setVisibility(View.INVISIBLE);
					} else {
						((Button) rootView.findViewById(R.id.prev_image))
								.setVisibility(View.VISIBLE);
					}
					if (pos == imagesList.size() - 1) {
						((Button) rootView.findViewById(R.id.next_image))
								.setVisibility(View.INVISIBLE);
					} else {
						((Button) rootView.findViewById(R.id.next_image))
								.setVisibility(View.VISIBLE);
					}
				}

				@Override
				public void onPageScrolled(int arg0, float arg1, int arg2) {
				}

				@Override
				public void onPageScrollStateChanged(int arg0) {
				}
			};

			mPager.setOnPageChangeListener(changer);

			changer.onPageSelected(0);

			((Button) rootView.findViewById(R.id.prev_image))
					.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							mPager.setCurrentItem(mPager.getCurrentItem() - 1,
									true);
						}
					});

			((Button) rootView.findViewById(R.id.next_image))
					.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							mPager.setCurrentItem(mPager.getCurrentItem() + 1,
									true);
						}
					});

			for (final ArchitectVo a : architectsList) {
				Button architect = new Button(getActivity());
				architect.setTextAppearance(getActivity(),
						android.R.style.TextAppearance_Medium);

				TableRow.LayoutParams buttonParams = new TableRow.LayoutParams(
						TableRow.LayoutParams.FILL_PARENT,
						TableRow.LayoutParams.WRAP_CONTENT, 1f);

				architect.setLayoutParams(buttonParams);
				architect.setText(a.getName());

				if (a.getBiography() == null
						|| "".compareTo(a.getBiography()) == 0) {
					architect.setEnabled(false);
					architect.setClickable(false);
				} else {
					architect.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							Intent detailIntent = new Intent(getActivity(),
									ArchitectDetailActivity.class);
							detailIntent
									.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
											| Intent.FLAG_ACTIVITY_NEW_TASK);
							detailIntent.putExtra(
									ArchitectDetailFragment.ARG_ITEM_ID, a
											.getId().toString());
							startActivity(detailIntent);
							getActivity().finish();
						}
					});
				}

				TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams(
						TableLayout.LayoutParams.FILL_PARENT,
						TableLayout.LayoutParams.WRAP_CONTENT, 1);
				rowParams.setMargins(0, 5, 0, 0);

				TableRow row = new TableRow(getActivity());
				row.setLayoutParams(rowParams);
				row.addView(architect);

				((TableLayout) rootView.findViewById(R.id.poiTableLayout))
						.addView(row);
			}

			if (poi.getLatitude() != 0 && poi.getLongitude() != 0) {
				((ImageButton) rootView.findViewById(R.id.showOnMap))
						.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								Intent detailIntent = new Intent(getActivity(),
										Tour.class);
								detailIntent.putExtra(Tour.ARG_POI_ID, poi
										.getId().toString());

								startActivity(detailIntent);
							}
						});
			} else {
				((ImageButton) rootView.findViewById(R.id.showOnMap))
						.setVisibility(View.GONE);
			}

		}

		return rootView;
	}
}
